package com.lys.book;

import com.lys.book.dao.BookInfoDAO;
import com.lys.book.model.BookInfo;
import com.lys.book.utils.ConnDB;
import com.sun.org.apache.xml.internal.security.Init;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.SQLException;

public class MyTable extends JFrame implements ActionListener {
    private JTable table;
    private DefaultTableModel model;

    private BookInfoDAO bookInfoDAO = new BookInfoDAO(ConnDB.getConnection());
    private JTextField bookNameField, authorField, isbnField,publisherField, priceField;
    private JButton addButton, updateButton, deleteButton, searchButton, logoutButton;
    public Object[][] data = new Object[][]{
            {"书1", "张三","上海",20,"1111"},
            {"书2", "张三","上海",22,"1111"},
            {"书3", "张三","上海",25,"1111"},
            {"书4", "张三","上海",18,"1111"},
    };
    private Object[] columnNames = {"书名", "作者","出版社","价格","ISBN"};

    public void init(){
        try {
            ResultSet set = ConnDB.query("select * from book_info", new Object[]{});
            Object[][] arrays = ConnDB.convertResultSetToObjectArray(set);
            data = arrays;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public MyTable() {
        setTitle("软件公益图书管理");
        init();
        // 创建表格
        model = new DefaultTableModel(data, columnNames);
        table = new JTable(model);

        // 创建输入框和按钮
        bookNameField = new JTextField(10);
        authorField = new JTextField(10);
        isbnField = new JTextField(10);
        publisherField=new JTextField(10);
        priceField=new JTextField(10);
        addButton = new JButton("添加");
        updateButton = new JButton("修改");
        deleteButton = new JButton("删除");
        searchButton = new JButton("查询");
        logoutButton = new JButton("退出");

        // 添加事件监听器
        addButton.addActionListener(this);
        updateButton.addActionListener(this);
        deleteButton.addActionListener(this);
        searchButton.addActionListener(this);
        logoutButton.addActionListener(this);

        // 创建面板并添加组件
        JPanel panel1 = new JPanel(new FlowLayout());
        panel1.add(new JLabel("书名"));
        panel1.add(bookNameField);
        panel1.add(new JLabel("作者"));
        panel1.add(authorField);
        panel1.add(new JLabel("ISBN"));
        panel1.add(isbnField);
        panel1.add(new JLabel("出版社"));
        panel1.add(publisherField);
        panel1.add(new JLabel("价格"));
        panel1.add(priceField);

        JPanel panel2 = new JPanel(new FlowLayout());
        panel2.add(addButton);
        panel2.add(updateButton);
        panel2.add(deleteButton);
        panel2.add(searchButton);
        panel2.add(logoutButton);

        // 添加组件到窗口
        Container container = getContentPane();
        container.setLayout(new BorderLayout(5, 5));
        container.add(panel1, BorderLayout.NORTH);
        container.add(new JScrollPane(table), BorderLayout.CENTER);
        container.add(panel2, BorderLayout.SOUTH);

        // 设置窗口属性
        setSize(900, 300);
        setLocationRelativeTo(null);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    // 实现事件监听器接口
    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == addButton) {  // 添加
            BookInfo bookInfo = new BookInfo();
            bookInfo.setIsbn(isbnField.getText());
            bookInfo.setName(bookNameField.getText());
            bookInfo.setAuthor(authorField.getText());
            bookInfo.setPublisher(publisherField.getText());
            bookInfo.setPrice(priceField.getText());
            try {
                bookInfoDAO.insert(bookInfo);
                String[] row = new String[]{bookNameField.getText(), authorField.getText(),publisherField.getText(),priceField.getText(), isbnField.getText()};
                model.addRow(row);
                clearFields();
                JOptionPane.showMessageDialog(this,"添加成功！");
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(this,"添加失败！");
                throw new RuntimeException(ex);
            }

        } else if (e.getSource() == updateButton) {  // 修改
            int row = table.getSelectedRow();
            if (row != -1) {
                BookInfo book = new BookInfo();
                book.setName(bookNameField.getText());
                book.setAuthor(authorField.getText());
                book.setPublisher(publisherField.getText());
                book.setPrice(priceField.getText());
                book.setIsbn(isbnField.getText());
                try {
                    bookInfoDAO.update(book);
                    model.setValueAt(bookNameField.getText(), row, 0);
                    model.setValueAt(authorField.getText(), row, 1);
                    model.setValueAt(publisherField.getText(),row, 2);
                    model.setValueAt(priceField.getText(), row, 3);
                    model.setValueAt(isbnField.getText(), row, 4);
                    clearFields();
                    JOptionPane.showMessageDialog(this,"修改成功！");
                } catch (SQLException ex) {
                    JOptionPane.showMessageDialog(this,"修改失败！");
                    throw new RuntimeException(ex);

                }

            }
        } else if (e.getSource() == deleteButton) {  // 删除
            int row = table.getSelectedRow();
            if (row != -1) {
                String isbn = (String) table.getValueAt(row, 4);
                try {
                    bookInfoDAO.delete(isbn);
                    model.removeRow(row);
                    clearFields();
                    JOptionPane.showMessageDialog(this,"删除成功！");
                } catch (SQLException ex) {
                    JOptionPane.showMessageDialog(this,"删除失败！");
                    throw new RuntimeException(ex);
                }

            }
        } else if (e.getSource() == searchButton) {  // 查询
            String bookName = bookNameField.getText();
            String author = authorField.getText();
            String isbn = isbnField.getText();
            String publisher = publisherField.getText();
            String price = priceField.getText();
            for (int i = 0; i < table.getRowCount(); ++i) {
                if (bookName.equals(table.getValueAt(i, 0)) ||
                        author.equals(table.getValueAt(i, 1)) ||
                        publisher.equals(table.getValueAt(i, 2))||price.equals(table.getValueAt(i, 3))||isbn.equals(table.getValueAt(i, 4))) {
                    table.setRowSelectionInterval(i, i);
                    return;
                }
            }
            JOptionPane.showMessageDialog(this, "未找到符合条件的记录！");
        } else if (e.getSource() == logoutButton) {  // 退出
            dispose();  // 关闭当前窗口
            new LoginWindow();  // 打开登录窗口
        }
    }

    // 清空输入框
    private void clearFields() {
        bookNameField.setText("");
        authorField.setText("");
        isbnField.setText("");
        publisherField.setText("");
        priceField.setText("");
    }

    public static void main(String[] args) {
        new LoginWindow();
    }
}

class LoginWindow extends JFrame implements ActionListener {
    private JTextField userField;
    private JPasswordField passwordField;
    private JButton loginButton, cancelButton;
    private String correctUser = "1";
    private String correctPass = "1";

    public LoginWindow() {
        setTitle("用户登录");

        // 创建输入框和按钮
        userField = new JTextField(20);
        passwordField = new JPasswordField(20);
        loginButton = new JButton("登录");
        cancelButton = new JButton("取消");

        // 添加事件监听器
        loginButton.addActionListener(this);
        cancelButton.addActionListener(this);

        // 创建面板并添加组件
        JPanel panel1 = new JPanel(new GridLayout(2, 1, 5, 5));
        panel1.add(new JLabel("用户："));
        panel1.add(new JLabel("密码："));

        JPanel panel2 = new JPanel(new GridLayout(2, 1, 5, 5));
        panel2.add(userField);
        panel2.add(passwordField);

        JPanel panel3 = new JPanel(new FlowLayout());
        panel3.add(loginButton);
        panel3.add(cancelButton);

        // 添加组件到窗口
        Container container = getContentPane();
        container.setLayout(new BorderLayout(5, 5));
        container.add(panel1, BorderLayout.WEST);
        container.add(panel2, BorderLayout.CENTER);
        container.add(panel3, BorderLayout.SOUTH);

        // 设置窗口属性
        setSize(300, 150);
        setLocationRelativeTo(null);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    // 实现事件监听器接口
    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == loginButton) {  // 登录
            String user = userField.getText().trim();
            String pass = new String(passwordField.getPassword()).trim();
            if (user.isEmpty() || pass.isEmpty()) {  // 用户名或密码为空
                JOptionPane.showMessageDialog(this, "用户名或密码不能为空！");
            } else if (user.equals(correctUser) && pass.equals(correctPass)) {  // 用户名和密码正确
                dispose();  // 关闭当前窗口
                new MyTable();  // 打开表格窗口
            } else {  // 用户名或密码错误
                JOptionPane.showMessageDialog(this, "用户名或密码错误！");
            }
        } else if (e.getSource() == cancelButton) {  // 取消
            System.exit(0);  // 退出程序
        }
    }



}
